<?php
namespace app\h5api\controller;

use app\common\model\Aftersales;
use app\common\model\GoodsRecord;
use app\common\model\Order as OrderModel;
use app\common\model\Cart;
use app\common\model\OrderExpress;
use app\common\model\Reserveorder;
use app\common\model\Shops;
use app\common\service\ServiceAdmin;

class Order extends Base
{
	/**
	 * @route('h5/GetOrderList','get')
	 * 普通商品和兑换商品订单列表
	 */
	public function GetOrderList()
	{
		$OrderModel = new OrderModel();
        $limit = input('get.limit') ? input('get.limit') : 6;
		$status = input('get.status') ? input('get.status') : '';
		$pname = input('get.product_name') ? input('get.product_name') : '';
		$iscomment = input('get.is_comment') ? input('get.is_comment') : '';
		$class_ids = [1,2];
		$data = $OrderModel->shops_order_list([
		    'user_id'=>$this->_userid,
            'order_status'=>$status,
            'product_name' => $pname,
            'class_ids' => $class_ids,
            'is_comment' => $iscomment],'o.order_id desc',$limit,false,[
			'o.order_id','o.shop_id','s.shop_name','o.pay_amount','o.order_status','o.pay_status','o.express_fee','s.imagesurl','o.order_type','points','o.tracking_number','o.shiping_time'
		],[
			'detail_id','order_id','product_id','product_name','p_s_id','p_s_name','cover_url','sale_price','amount','cover_url','quantity','growth_coin','growth_coin_amount'
		]);
		$data = [
			'data'=>$data['data'],
			"total"=> $data['page']['total'],
			"per_page"=> $data['page']['per_page'],
			"current_page"=> $data['page']['current_page'],
			"last_page"=> $data['page']['last_page'],
		];
		$this->result($data,1,'操作成功');
	}

	/**
	 * @route('h5/GetOtherOrders','get')
	 * 爱心商品和团餐商品订单列表
	 */
	public function GetOtherOrders()
	{
		$OrderModel = new OrderModel();
		$limit = input('get.limit') ? input('get.limit') : 6;
		$status = input('get.status') ? input('get.status') : '';
		$pname = input('get.product_name') ? input('get.product_name') : '';
		$shopname = input('get.shop_name') ? input('get.shop_name') : '';
		$iscomment = input('get.is_comment') ? input('get.is_comment') : '';
		$isuse = input('get.is_use') ? input('get.is_use') : '';
		$classname = input('get.class_name');
		$class_id = '';
		if($classname == 'love'){
		    $class_id = 3;
        } else if($classname == 'team'){
		    $class_id = 4;
        } else {
		    $this->result('',-1,'订单类型有误');
        }
		$where = [
            'user_id'=>$this->_userid,
            'order_status'=>$status,
            'product_name' => $pname,
            'shop_name' => $shopname,
            'class_id' => $class_id,
            'is_use' => $isuse,
            'is_del' => 1
        ];
		if(!empty($iscomment)){
            $where['is_comment'] = $iscomment;
        }
		$data = $OrderModel->loveandteam_order_list($where,'o.order_id desc',$limit,false,[
			'o.order_id','o.shop_id','s.shop_name','o.pay_amount','o.order_status','o.pay_status','o.express_fee','s.imagesurl','o.order_type','o.is_comment','gr.status as is_use'
		],[
			'detail_id','order_id','product_id','product_name','p_s_name','cover_url','sale_price','amount','cover_url','quantity','is_comment'
		]);
		$data = [
			'data'=>$data['data'],
			"total"=> $data['page']['total'],
			"per_page"=> $data['page']['per_page'],
			"current_page"=> $data['page']['current_page'],
			"last_page"=> $data['page']['last_page'],
		];
		$this->result($data,1,'操作成功');
	}

    /**
     * @route('h5/GetOrderDetail','get')
     * 获取普通商品和兑换商品订单详情
     */
    public function GetOrderDetail()
    {
        $order_id = input('get.order_id');
        $user = $this->GetUserInfo();
        $data = [];
        $orderModel = new OrderModel();
        $where = [
            ['user_id','=',$user['user_id']],
            ['order_id','=',$order_id],
            ['order_type','in',[1,2]],
            ['is_del','=',1]
        ];
        $order = $orderModel->getOne($where);
        if(empty($order)){
            $this->result('',-1,'用户不存在的订单');
        }
        $data['order'] = $order->toArray();
        $data['order']['total'] = 0;
        $item = 'od.*,s.shop_id';
        $detail = $orderModel->api_order_details($order_id,$item);
//        var_dump($detail);die;
        if(empty($order)){
            $this->result('',-1,'不存在的订单详情');
        }
        $shop_ids = array_column($detail,'shop_id');
        $shopModel = new Shops();
//        var_dump($shop_ids);die;
        $shops = $shopModel->get_list(['shop_ids'=>$shop_ids],'','shop_id,shop_name,shop_phone,address,province,city,area,imagesurl')->toArray();
        $shops = array_column($shops,null,'shop_id');
//        var_dump($shops);die;
        foreach($detail as $value){
            $data['order']['total'] += $value['quantity'];
            $detailinfo[$value['shop_id']]['shopinfo'] = $shops[$value['shop_id']];
            $detailinfo[$value['shop_id']]['detailinfo'][] = $value;
        }
        $data['productinfo'] = array_values($detailinfo);
        $this->result($data,1,'返回信息');
    }

    /**
     * @route('h5/GetOtherDetail','get')
     * 获取爱心餐团餐订单详情
     */
    public function GetOtherDetail()
    {
        $order_id = input('get.order_id');
        $user = $this->GetUserInfo();
        $data = [];
        $orderModel = new OrderModel();
        $where = [
            ['o.user_id','=',$user['user_id']],
            ['o.order_id','=',$order_id],
            ['o.order_type','in',[3,4]],
            ['o.is_del','=',1]
        ];
        $join = [
            ['ddt_goods_record gr','o.order_id = gr.order_id'],
            ['ddt_shops s','o.shop_id = s.shop_id']
        ];
        $item = 'o.*,gr.status as is_use,gr.access_code,gr.draw_time,gr.get_time';
        $shopitem = 's.shop_name,s.shop_phone,s.address,s.province,s.city,s.area,s.imagesurl';
        $item .= ','.$shopitem;
        $order = $orderModel->getJoinOrder($where,$item,$join);
        if(empty($order)){
            $this->result('',-1,'用户不存在的订单');
        }
        $item = 'od.*';
        $detail = $orderModel->api_order_details($order_id,$item,[['ddt_order o','od.order_id = o.order_id']]);
        if(empty($order)){
            $this->result('',-1,'不存在的订单详情');
        }

        $data = [
            'order' => $order->toArray(),
            'detail' => $detail,
        ];
        if($order['order_type'] == 4){
            $reserveModel = new Reserveorder();
            $reserve_info = $reserveModel->where('order_id','=',$order_id)->find();
            $data['reserve_info'] = $reserve_info;
        }
        $this->result($data,1,'返回信息');
    }

	/**
	 * @route('h5/Settlement','post')
	 * 购物车结算
	 */
	public function Settlement()
	{
		$ids = input('post.cart_ids');
		$receive_id = input('post.receive_id');
		$CartModel = new Cart();
		$user = $this->GetUserInfo();
		$data = $CartModel->Settlement($user,$ids,$receive_id);
		if(!$data){
			$this->result([],-1,$CartModel->getError());
//			$this->result([],-1,'商铺或者商品已下架');
		}
		$this->result($data,1,'操作成功');
	}

	/**
	 * @route('h5/UncommonSettlement','post')
	 * 非普通商品结算
	 */
	public function UncommonSettlement()
	{
        $product_id = input('post.product_id');
        $stock_id = input('post.stock_id');
        $quantity = input('post.quantity');
        $receive_id = input('post.receive_id');
        $OrderModel = new OrderModel();
		$user = $this->GetUserInfo();
		$data = $OrderModel->checkplace($user,$product_id,$stock_id,$quantity,$receive_id);
		if(!$data){
			$this->result([],-1,$OrderModel->getError());
		}
		$this->result($data,1,'操作成功');
	}

    /**
     * @route('h5/UserRemind')
     * 用户提醒订单发货
     */
    public function UserRemind()
    {
        $orderModel = new OrderModel();
        $where = [
            'order_id' => input('post.order_id'),
            'user_id' => $this->_userid,
        ];
        $rs = $orderModel->operateremind($where);
        if($rs === false){
            $this->result('',-1,$orderModel->getError());
        }
        $this->result('',1,'操作成功');
    }

    /**
     * @route('h5/UserCancel')
     * 用户取消订单
     */
    public function UserCancel()
    {
        $orderModel = new OrderModel();
        $where = [
            'order_id' => input('post.order_id'),
            'user_id' => $this->_userid,
        ];
        $rs = $orderModel->operatecancel($where);
        if($rs === false){
            $this->result('',-1,$orderModel->getError());
        }
        $this->result('',1,'操作成功');
    }

    /**
     * @route('h5/UserSure')
     * 用户确认订单收货
     */
    public function UserSure()
    {
        $orderModel = new OrderModel();
        $where = [
            'order_id' => input('post.order_id'),
            'user_id' => $this->_userid,
        ];
        $rs = $orderModel->operatesure($where);
        if($rs === false){
            $this->result('',-1,$orderModel->getError());
        }
        $this->result('',1,'操作成功');
    }

    /**
     * @route('h5/UserDelete')
     * 用户删除订单
     */
    public function UserDelete()
    {
        $orderModel = new OrderModel();
        $where = [
            'order_id' => input('post.order_id'),
            'user_id' => $this->_userid,
        ];
        $rs = $orderModel->operatedelete($where);
        if($rs === false){
            $this->result('',-1,$orderModel->getError());
        }
        $this->result('',1,'操作成功');
    }

    /**
     * @route('h5/UserComment')
     * 用户获取单个订单详情和订单评价操作
     */
    public function UserComment()
    {
        $orderModel = new OrderModel();
        $orderid = input('get.order_id');
        $detailid = input('get.detail_id');
        $userinfo = $this->GetUserInfo();
        $where = [
            ['o.order_id','=',$orderid],
            ['o.user_id','=',$userinfo['user_id']],
            ['od.detail_id','=',$detailid],
        ];
        $join = [
            ['ddt_orderdetail od','o.order_id = od.order_id'],
        ];
        $detail = $orderModel->getJoinOrder($where,'od.*',$join);
        if(input('post.handle') == 'submit') {
            $params = input('post.');
            //        var_dump($params);die;
            $where = [
                'order_id' => $params['order_id'],
                'detail_id' => $params['detail_id'],
                'user_id' => $this->_userid,
            ];
            $rs = $orderModel->operatecomment($where, $params);
            if ($rs === false) {
                $this->result('', -1, $orderModel->getError());
            }
            $this->result('', 1, '操作成功');
        }
        $this->result($detail,1,'返回');
    }

    /**
     * @route('h5/UserAfterSaleList')
     * 用户申请售后订单列表
     */
    public function UserAfterSaleList()
    {
        $afterModel = new Aftersales();
        $status = input('get.status',0);
        $product_name = input('get.product_name','');
        $where = [
            'user_id' => $this->_userid,
            'product_name' => $product_name,
            'status' => $status,
            'is_show' => 1,
            'is_del' => 1,
        ];
        $item = 'as.a_s_id,as.order_id,as.shop_id,as.content,as.images,as.a_s_status,as.add_time as as_time,s.shop_name,s.shop_phone,s.imagesurl,o.pay_amount,o.order_type';
        $join = [
            ['ddt_order o','as.order_id = o.order_id'],
            ['ddt_shops s','as.shop_id = s.shop_id'],
        ];
        $data = $afterModel->get_aftersales_list($where,$item,'',$this->limit,$join,false,true)->toArray();
        $this->result($data,1,'操作成功');
    }

    /**
     * @route('h5/AfterSaleDetail','get')
     * 售后订单详情
     */
    public function AfterSaleDetail()
    {
        $asid = input('get.a_s_id');
        $user = $this->GetUserInfo();
        $data = [];
        $afterModel = new Aftersales();
        $condition = [
            ['as.user_id','=',$user['user_id']],
            ['a_s_id','=',$asid],
            ['is_show','=',1],
            ['o.is_del','=',1],
        ];
        $after = $afterModel
            ->alias('as')
            ->leftJoin('ddt_order o','as.order_id = o.order_id')
            ->where($condition)
            ->field('a_s_id,as.order_id,content,images,a_s_status,add_time,is_refund,a_s_type')
            ->find();
//        var_dump($after);die;
        if(empty($after)){
            $this->result('',-1,'用户不存在的申请');
        }
        $data['after'] = $after->toArray();
        $data['after']['images'] = explode(',',$data['after']['images']);
        $orderModel = new OrderModel();
        $where = [
            ['user_id','=',$user['user_id']],
            ['order_id','=',$data['after']['order_id']],
            ['is_del','=',1]
        ];
        $order = $orderModel->getOne($where);
        if(empty($order)){
            $this->result('',-1,'用户不存在的订单');
        }
        $data['order'] = $order->toArray();
        $data['order']['total'] = 0;
        $item = 'od.*,s.shop_id';
        $detail = $orderModel->api_order_details($data['after']['order_id'],$item);
//        var_dump($detail);die;
        if(empty($order)){
            $this->result('',-1,'不存在的订单详情');
        }
        $shop_ids = array_column($detail,'shop_id');
        $shopModel = new Shops();
//        var_dump($shop_ids);die;
        $shops = $shopModel->get_list(['shop_ids'=>$shop_ids],'','shop_id,shop_name,shop_phone,address,province,city,area,imagesurl')->toArray();
        $shops = array_column($shops,null,'shop_id');
//        var_dump($shops);die;
        foreach($detail as $value){
            $data['order']['total'] += $value['quantity'];
            $detailinfo[$value['shop_id']]['shopinfo'] = $shops[$value['shop_id']];
            $detailinfo[$value['shop_id']]['detailinfo'][] = $value;
        }
        if($order['order_type'] == 4){
            $recordModel = new GoodsRecord();
            $record = $recordModel->getOne([['user_id','=',$user['user_id']], ['order_id','=',$order['order_id']]],'access_code,draw_time');
            $data['record'] = $record;
            $reserveModel = new Reserveorder();
            $reserve = $reserveModel->getOne([['order_id','=',$order['order_id']]]);
            $data['reserve_info'] = $reserve;
        }
        $data['productinfo'] = array_values($detailinfo);
        $this->result($data,1,'返回信息');
    }
    /**
     * @route('h5/UserAfterSales')
     * 用户申请售后
     */
    public function UserAfterSales()
    {
        $orderModel = new OrderModel();
        $params = input('post.');
//        var_dump($params);die;
        $where = [
            'order_id' => $params['order_id'],
            'detail_id' => $params['detail_id'],
            'user_id' => $this->_userid,
        ];
        $rs = $orderModel->operateaftersales($where,$params);
        if($rs === false){
            $this->result('',-1,$orderModel->getError());
        }
        $this->result($rs,1,'操作成功');
    }


    /**
     * @route('h5/UserWithdrawal')
     * 用户撤销售后申请
     */
    public function UserWithdrawal()
    {
        $afterModel = new Aftersales();
        $where = [
            'a_s_id' => input('post.a_s_id'),
            'user_id' => $this->_userid,
        ];
        $rs = $afterModel->operatewithdrawal($where);
        if($rs === false){
            $this->result('',-1,$afterModel->getError());
        }
        $this->result('',1,'操作成功');
    }

    /**
     * @route('h5/UserReserveOrderList','get')
     * 用户预约订单列表
     */
    public function UserReserveOrderList()
    {
        $orderModel = new Reserveorder();
        $where = [
            'user_id' => $this->_userid,
            'status' => input('get.status'),
            'shop_name' => input('get.shop_name'),
        ];
        $rs = $orderModel->GetReserveOrderList($where,'*',$this->limit)->toArray();
        $this->result($rs,1,'操作成功');
    }

    /**
     * @route('h5/UserReserveOrderDetail','get')
     * 用户预约订单详情
     */
    public function UserReserveOrderDetail()
    {
        $orderModel = new Reserveorder();
        $order_id = input('get.order_id');
        if(empty($order_id)){
            $this->result([],-1,'订单参数有误');
        }
        $where = [
            'user_id' => $this->_userid,
            'order_id' => $order_id,
        ];
        $rs = $orderModel->GetReserveOrderDetail($where);
        if(empty($rs)){
            $this->result([],-1,'无此订单详情');
        }
        $rs['place_time'] = date('Y-m-d H:i',$rs['place_time']);
        $this->result($rs,1,'操作成功');
    }

    /**
     * @route('h5/UserCancelReserve','post')
     * 用户取消预约
     */
    public function UserCancelReserve()
    {
        $orderModel = new Reserveorder();
        $where = [
            'order_id' => input('post.order_id'),
            'user_id' => $this->_userid,
        ];
        $rs = $orderModel->operatecancelreserve($where);
        if($rs === false){
            $this->result('',-1,$orderModel->getError());
        }
        $this->result('',1,'操作成功');
    }

	/**
	 * @route('h5/OrderExpress')
	 * 查询快递接口
	 */
	public function Express()
	{
		// 订单ID
		$orderId = input('order_id');
		// 物流信息表
		$ServiceAdmin = new ServiceAdmin();
		$orderexpress_data = $ServiceAdmin->CheckExpress($orderId);
		if(!$orderexpress_data){
			$this->result([],-1,$ServiceAdmin->getError());
		}
		$this->result($orderexpress_data,1);
	}


    /**
     * @route('h5/sureget')
     * 用户确认领取爱心餐
     */
    public function sureget()
    {
        $order_id = input('order_id');
        $order_type = [3,4];
        $ordersModel = new OrderModel();

        $recordModel = new GoodsRecord();
        $code = input('access_number');
        $where = [
            ['o.pay_status','=',2],
            ['o.order_status','=',4],
            ['o.order_type','in',$order_type],
            ['o.user_id','=',$this->_userid],
        ];
        isset($code)?$where[] = ['gr.access_code','=',$code]:'';
        isset($order_id)?$where[] = ['o.order_id','=',$order_id]:'';
        if(!isset($order_id) && !isset($code)){
            $this->result('',-1,'类型有误');
        }
//            echo "<pre>";
//            print_r($where);
        $record = $ordersModel->getJoinOrder($where,'gr.*',[['ddt_goods_record gr','o.order_id = gr.order_id']]);
//            var_dump($record);die;
        if(empty($record)){
            $this->result('',-1,'查询不到订单');
        }
        $record = $record->toArray();
        if($record['status'] == 2){
            $this->result('',-1,'该订单已领取');
        }
        $res = $recordModel->EditRecord(['status'=>2,'get_time'=>time()],$record['g_r_id']);
        if(!$res){
            $this->result('',-1,$recordModel->getError());
        }
        $this->result('',1,'操作成功');
    }
}
